package net.didactylos.helpline.action;

import java.util.List;

import org.hibernate.Session;

import net.didactylos.helpline.data.Message;
import net.didactylos.helpline.data.Template;
import net.didactylos.helpline.servlet.EmailManager;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;

public class ApproveAction extends HelplineActionBean
{
	
	protected Message message;
	
	protected Message reply;
	
	public Message getMessage()
	{
		return message;
	}

	public void setMessage(Message message)
	{
		this.message = message;
	}

	public Message getReply()
	{
		return reply;
	}

	public void setReply(Message reply)
	{
		this.reply = reply;
	}
	
	@Before(stages=LifecycleStage.BindingAndValidation)
	public Resolution preLoadReply()
	{
		reply = getContext().getMessage();
		if (reply != null)
		{
			message = reply.getInReplyTo();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		if (reply == null)
		{
			Session session = getContext().getSession();
			
			List<Message> approvals = session
			.createQuery("from Message as msg where msg.status=2")
			.list();
			
			if (approvals.size() == 0)
			{
				getContext().getMessages().add(new LocalizableMessage("approveNothingMessage"));
				return new RedirectResolution("/");    
			}
			
			reply = approvals.get(0);
			message = reply.getInReplyTo();
			
			//reply.setStatus(0);
			getContext().setMessage(reply);
			session.update(reply);
			session.getTransaction().commit();
		}
		
		return new ForwardResolution("approve.jspx");
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution approve()
	{
		//reply.setStatus(4);
		reply.setTemplate((Template) getContext().getSession().createCriteria(Template.class).uniqueResult());
		
		getContext().getSession().update(reply);
		
		EmailManager.sendEmail(reply);
		getContext().getSession().getTransaction().commit();
		
		getContext().setMessage(null);
		
		getContext().getMessages().add(new LocalizableMessage("approveSuccessMessage", getMessage()
				.getAuthor().getDisplayName()));
		
        return new RedirectResolution("/");
	}
}
